<template>
  <div class="departments-box">
    <el-card>
      <template #header> 组织架构 </template>
      <div class="mian">
        <treeItem :item-data="topInfo" />
        <hr>
        <el-tree
          :data="treeData"
          default-expand-all
          :props="{ label: 'name', children: 'children' }"
        >
          <template v-slot="{ data }">
            <treeItem :item-data="data" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 弹框组件 -->
    <Add :init-data="initData" @getData="getData" />
  </div>
</template>

<script>
import treeItem from './components/treeItem.vue'
import Add from './components/Add.vue'
// 导入调用api
import { companyDepartment } from '@/api/departments'
export default {
  components: {
    treeItem,
    Add
  },
  data() {
    return {
      topInfo: {
        isTop: true,
        name: '传智教育',
        manager: '负责人',
        id: ''
      },
      treeData: [],
      initData: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取所有部门信息
    async getData() {
      const res = await companyDepartment()
      // this.treeData = res.data.depts
      // 找顶级部门
      this.initData = res.data.depts
      this.treeData = this.changData(res.data.depts, '')
      // console.log(res.data.depts)
    },
    // 树形转换
    changData(arr, str) {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments-box {
  padding: 0 15px;
  .mian {
    width: 80%;
    margin: 0 auto;
  }
}
</style>
